﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Jungle.Code.BLL;
using Jungle.Code.Utils;
using System.Collections.Generic;
using Jungle.Code.DAL;

using Jungle.Modules;
using Jungle.Code.BookManager;
using System.Drawing;



namespace Jungle.Modules.Books
{
    public partial class BooksAdmin: BaseAdminModule
    {
        string cmd = "";
        string id = "";

        protected override void OnInit(EventArgs e)
        {
            if (Request["cmd"] != null)
                cmd = Request["cmd"];
            if (Request["bId"] != null)
                id = Request["bId"];

            

            switch (cmd)
            {
                case "view":
                    GlobalMenu.ActiveViewIndex = 2;
                    break;
                case "viewHidden":
                    GlobalMenu.ActiveViewIndex = 2;
                    break;
                case "add":
                    GlobalMenu.ActiveViewIndex = 1;
                    btn_AddNewBook.Visible = true;
                    break;
                case "edit":
                    GlobalMenu.ActiveViewIndex = 1;
                    PrepareView();
                    btn_SaveBookChanges.Visible = true;
                    break;
                default:
                    GlobalMenu.ActiveViewIndex = 0;
                    break;
            }
            base.OnInit(e);
        }
        public override void FillBaseInfo()
        {
            sysName = "Books";
        }
        public override void Main()
        {
        }


        public void FillDdl()
        {
           
        }
        //------------------------------------------------------------------
        public void PrepareView()
        {
            if (cmd == "edit" && id != null)
            {
                Book bToEdit = new Book();
                bToEdit.GetById(Convert.ToInt32(id));

                txt_BookTitle.Text = bToEdit.Title.Trim();
                txt_Author.Text = bToEdit.Author.Trim();
                //***********
                txt_BookDescription.Text = bToEdit.Description.Trim();
                txt_Format.Text = bToEdit.Format.Trim();
                txt_BookLanguage.Text = bToEdit.Language.Trim();
                txt_BookPagesCount.Text = bToEdit.PagesCount.ToString().Trim();
                txt_BookPrice.Text = bToEdit.Price.ToString().Trim();
                txt_BookPublisher.Text = bToEdit.Publisher.Trim();
                txt_BookPubYear.Text = bToEdit.PubYear.ToString().Trim();
                txt_BookSeries.Text = bToEdit.Series.Trim();
                ddl_BookQuality.SelectedValue = bToEdit.Quality.Trim();
                ddl_Visible.SelectedIndex = Convert.ToInt32(bToEdit.Visible);
            }
            else { Response.Redirect("/Modules.aspx?mod=Books&cmd=view"); }
        }
        //------------------------------------------------------------------
        public void AddBook(object sender, EventArgs e)
        {
            string err = "";
            Book newBook = new Book();

            if (txt_BookTitle.Text != "") { newBook.Title = txt_BookTitle.Text.Trim(); } else { err = "Обязательно заполните поле \"Название\""; }
            if (txt_Author.Text != "") { newBook.Author = txt_Author.Text.Trim(); }
            newBook.CategoryId = 1;
            if (txt_BookDescription.Text != "") { newBook.Description = txt_BookDescription.Text; }
            if (txt_Format.Text != "") { newBook.Format = txt_Format.Text; }
            if (txt_BookLanguage.Text != "") { newBook.Language = txt_BookLanguage.Text; }
            try { newBook.PagesCount = Convert.ToInt32(txt_BookPagesCount.Text); } catch { err = "Только целые числа в поле \"Количество страниц\""; }
            try { newBook.Price = Convert.ToInt32(txt_BookPrice.Text); } catch { err = "Только целые числа в поле \"Цена\""; }
            if (txt_BookPublisher.Text != "") { newBook.Publisher = txt_BookPublisher.Text.Trim(); }
            try { if (txt_BookPubYear.Text.Length < 5) { newBook.PubYear = Convert.ToInt32(txt_BookPubYear.Text); } else { err = "Только год в формате (0000), например: 2009"; } }
            catch { err = "Только год в формате (0000), например: 2009"; }
            newBook.Quality = ddl_BookQuality.SelectedItem.Text.Trim();
            if (txt_BookSeries.Text != "") { newBook.Series = txt_BookSeries.Text.Trim(); }
            newBook.SizeMb = 0;
            if (fu_Photo.HasFile)
            {
                newBook.ImagePath = SaveImage(fu_Photo);
            }
            else 
            {
                newBook.ImagePath = "no_photo";    
            }
            newBook.DownloadPath = "none";
            if (ddl_Visible.SelectedIndex == 0) { newBook.Visible = true; } else { newBook.Visible = false; }

            if (err != "") { lbl_Result.Text = err.Trim(); } else { newBook.Add(); Response.Redirect("Modules.aspx?mod=Books&cmd=view"); }


        }
        //------------------------------------------------------------------
        public string SaveImage(FileUpload file)
        {
            string mask = "qwertyuiopasdfghjklzxcvbnm";
            Random rnd = new Random();
            string rndstr = "";
            for (int i = 0; i < 6; i++)
            {
                rndstr += mask[rnd.Next(0, 24)];
            }
            string fname = "";
            try
            {
                System.Drawing.Image loadedImg = System.Drawing.Image.FromStream(file.PostedFile.InputStream);

                fname = "/UserFiles/Images/Content/Books/" + rndstr + file.FileName;

                int h = 170;

                int width = 100;

                double d1 = Math.Round((double)loadedImg.Width / width, 4);
                double d2 = Math.Round((double)loadedImg.Height / d1, 4);
                int height = Convert.ToInt32(d2);

                Bitmap imgOutput = new Bitmap(width, height);
                imgOutput.MakeTransparent();
                imgOutput.MakeTransparent(Color.Black);

                Graphics newGraphics = Graphics.FromImage(imgOutput);
                newGraphics.Clear(Color.FromArgb(0, 255, 255, 255));

                newGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                newGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                newGraphics.DrawImage(loadedImg, 0, 0, width, height);
                newGraphics.Flush();

                if (file.FileName.ToLower().EndsWith(".jpg") || file.FileName.ToLower().EndsWith(".jpeg"))
                    imgOutput.Save(Server.MapPath(fname), System.Drawing.Imaging.ImageFormat.Jpeg);
                if (file.FileName.ToLower().EndsWith(".png"))
                    imgOutput.Save(Server.MapPath(fname), System.Drawing.Imaging.ImageFormat.Png);
                if (file.FileName.ToLower().EndsWith(".gif"))
                    imgOutput.Save(Server.MapPath(fname), System.Drawing.Imaging.ImageFormat.Gif);
                if (file.FileName.ToLower().EndsWith(".tiff"))
                    imgOutput.Save(Server.MapPath(fname), System.Drawing.Imaging.ImageFormat.Tiff);
            }
            catch { fname = "ERROR"; }

            return fname;
        }
        //------------------------------------------------------------------
        public void UpdateBook(object sender, EventArgs e)
        {
            string err = "";
            Book newBook = new Book();

            if (txt_BookTitle.Text != "") { newBook.Title = txt_BookTitle.Text.Trim(); } else { err = "Обязательно заполните поле \"Название\""; }
            if (txt_Author.Text != "") { newBook.Author = txt_Author.Text.Trim(); }
            newBook.CategoryId = 1;
            if (txt_BookDescription.Text != "") { newBook.Description = txt_BookDescription.Text; }
            if (txt_Format.Text != "") { newBook.Format = txt_Format.Text; }
            if (txt_BookLanguage.Text != "") { newBook.Language = txt_BookLanguage.Text; }
            try { newBook.PagesCount = Convert.ToInt32(txt_BookPagesCount.Text); }
            catch { err = "Только целые числа в поле \"Количество страниц\""; }
            try { newBook.Price = Convert.ToInt32(txt_BookPrice.Text); }
            catch { err = "Только целые числа в поле \"Цена\""; }
            if (txt_BookPublisher.Text != "") { newBook.Publisher = txt_BookPublisher.Text.Trim(); }
            try { if (txt_BookPubYear.Text.Length < 5) { newBook.PubYear = Convert.ToInt32(txt_BookPubYear.Text); } else { err = "Только год в формате (0000), например: 2009"; } }
            catch { err = "Только год в формате (0000), например: 2009"; }
            newBook.Quality = ddl_BookQuality.SelectedItem.Text.Trim();
            if (txt_BookSeries.Text != "") { newBook.Series = txt_BookSeries.Text.Trim(); }
            newBook.SizeMb = 0;
            if (fu_Photo.HasFile)
            {
                newBook.ImagePath = SaveImage(fu_Photo);
            }            
            newBook.DownloadPath = "none";
            if (ddl_Visible.SelectedIndex == 0) { newBook.Visible = true; } else { newBook.Visible = false; }

            if (err != "") { lbl_Result.Text = err.Trim(); } else { newBook.Update(); Response.Redirect("Modules.aspx?mod=Books&cmd=view"); }
        }

    }
}